package com.korubo.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.korubo.kit.JwtUtils;
import com.korubo.kit.MD5Kit;
import com.korubo.kit.R;
import com.korubo.web.mapper.MenuMapper;
import com.korubo.web.model.Menu;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.korubo.web.model.User;
import com.korubo.web.mapper.UserMapper;
import com.korubo.web.service.UserService;

import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public R login(User user) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("name", user.getName()).eq("pwd", MD5Kit.digestHex(user.getPwd()));
        User user1 = userMapper.selectOne(query);
        if (user1 == null) {
            return R.fail("用户名或密码错误！");
        }
        user1.setPwd(null);
        //查询用户对应的角色和权限
        List<Menu> listMenu = menuMapper.findByUserId(user1.getId());
        //以树的方式
        List<Menu> menus = treeMenu(listMenu);
        //进行jwt加密
        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtUtils.createToken(user1));
        map.put("menus", menus);
        map.put("user", user1);
        return R.ok(map);
    }

    @Override
    public R list(User user) {
        QueryWrapper<User> query = new QueryWrapper<>();
        Page<User> userPage = userMapper.selectPage(new Page<>(user.getPageNum(), user.getPageSize()), query);
        return R.ok(userPage);
    }

    private List<Menu> treeMenu(List<Menu> listMenu) {
        //转成map
        Map<String, Menu> map = listMenu.stream().collect(HashMap::new, (k, v) -> k.put(v.getId(), v), HashMap::putAll);
        List<Menu> menus = new ArrayList<>();
        for (Menu menu : listMenu) {
            if (menu.getParentId() != null) {
                Menu parent = map.get(menu.getParentId());
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(menu);
            } else {
                menus.add(menu);
            }
        }
        //根据sort 进行排序
        menus.sort(Comparator.comparingInt(Menu::getSort));
        return menus;
        //返回
    }
}
